package com.czy.workflow.core.selector;

import com.czy.workflow.core.context.FlowContext;
import com.czy.workflow.core.exception.FlowException;
import com.czy.workflow.core.exception.FlowExpressionException;
import com.czy.workflow.core.exception.FlowNodeOperationInvalidException;
import com.czy.workflow.core.model.FlowBranch;
import com.czy.workflow.core.model.FlowNode;
import com.czy.workflow.core.model.TaskInfo;
import com.czy.workflow.core.util.ExpressionUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class OptionalNodeBranchSelector extends AbstractNodeBranchSelector{

    @Override
    public List<FlowNode> selectNextNode(FlowContext flowContext, TaskInfo taskInfo)
            throws FlowNodeOperationInvalidException {
        FlowNode node = taskInfo.getNode();
        List<FlowBranch> branches = flowContext.getFlowService().getNodeBranches(taskInfo.getFlowId(), node.getId());

        List<FlowBranch> validBranches = branches.stream().filter((FlowBranch tmp)-> (tmp.getOption() != null && tmp.getOption().equals(taskInfo.getOption()))).collect(
                Collectors.toList());

        if(validBranches.size() <= 0){
            throw new FlowNodeOperationInvalidException(taskInfo);
        }
        return getNodesByBranch(flowContext, validBranches);
    }
}
